import { useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { request } from '@/request';
import { useEnter } from '@/hooks';
import { AuthWrapper } from '@/components';

const Login = () => {
   const phoneRef = useRef<HTMLInputElement>(null);
   const pwdRef = useRef<HTMLInputElement>(null);
   const [msg, setMsg] = useState('');

   const handleSubmit = () => {
      const phone = phoneRef.current?.value;
      const password = pwdRef.current?.value;
      // 验证
      if (!phone || !password) {
         setMsg('请输入手机和密码');
         return;
      }
      request('/auth/login', {
         method: 'POST',
         data: {
            phone,
            password,
         },
         showSuccess: true,
         success: () => {
            location.href = '/';
         },
      });
      setMsg('');
   };
   useEnter(handleSubmit);
   return (
      <AuthWrapper>
         <form>
            <div className="form-item">
               <div className="form-item-content">
                  <label>手机</label>
                  <input ref={phoneRef} name="email" autoFocus />
               </div>
            </div>

            <div className="form-item">
               <div className="form-item-content">
                  <label>密码</label>
                  <input ref={pwdRef} type="password" />
               </div>
            </div>
            {msg && <p className="form-item-msg">{msg}</p>}
         </form>
         <div className="btn mt-4" onClick={handleSubmit}>
            登录
         </div>
         <div className="text-center text-sm my-3">
            <span>还没有账号？</span>
            <Link to="/register">点击注册</Link>
         </div>
      </AuthWrapper>
   );
};

export default Login;
